<template>
  <div class="risk-rules-page">
    <el-card>
      <!-- 顶部操作区域 -->
      <div class="header-actions">
        <el-button type="success" @click="handleAdd">新增</el-button>
      </div>

      <art-table
        :data="tableData"
        :loading="tableLoading"
        :border="true"
        :total="total"
        :current-page="formInline.page"
        :page-size="formInline.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :show-header-background="true"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="ruleName" label="规则名称" min-width="150" />
        <el-table-column prop="ruleType" label="规则类型" min-width="120">
          <template #default="scope">
            <span>{{ getRuleTypeText(scope.row.ruleType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '已发布' : '未发布' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column prop="updateTime" label="更新时间" min-width="180" />
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <button-table type="edit" text="编辑" @click="handleEdit(scope.row)" />
              <button-table
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                :text="scope.row.status === 1 ? '下架' : '发布'"
                @click="handleToggleStatus(scope.row)"
              />
              <button-table type="delete" text="删除" @click="handleDelete(scope.row)" />
            </div>
          </template>
        </el-table-column>
      </art-table>
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <RiskRuleForm v-model="dialogVisible.form" :data="currentData" @success="handleFormSuccess" />
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getAllRiskRule, updateRiskRule, deleteRiskRule } from '@/api/riskApi'
  import type {
    RiskRulePageParam,
    RiskRule,
    RiskRuleUpdateParam,
    RiskRuleDeleteParam
  } from '@/api/model/riskModel'
  import { ApiStatus } from '@/utils/http/status'
  import ArtTable from '@/components/Table/ArtTable.vue'
  import ButtonTable from '@/components/Form/ButtonTable.vue'
  import RiskRuleForm from './RiskRuleForm.vue'

  let formInline = ref<RiskRulePageParam>({
    page: 1,
    pageSize: 10
  })
  let tableLoading = ref(false)
  let dialogVisible = ref({
    form: false
  })
  let total = ref(0)
  let tableData = ref<RiskRule[]>([])
  let currentData = ref<RiskRule | null>(null)
  let isEdit = ref(false)

  // 规则类型映射
  const ruleTypeMap = {
    1: '类型1',
    2: '类型2',
    3: '类型3'
  }

  function getRuleTypeText(type?: number): string {
    return type ? ruleTypeMap[type as keyof typeof ruleTypeMap] || '未知类型' : '未知类型'
  }

  onMounted(() => {
    getAll(formInline.value)
  })

  // 获取风险规则列表
  async function getAll(params: RiskRulePageParam) {
    try {
      tableLoading.value = true
      const res = await getAllRiskRule(params)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data?.list || []
        total.value = res.data?.total || 0
      }
    } catch (error) {
      console.error('获取风险规则列表失败:', error)
      ElMessage.error('获取风险规则列表失败')
    } finally {
      tableLoading.value = false
    }
  }

  // 分页大小变化
  function handleSizeChange(size: number) {
    formInline.value.pageSize = size
    formInline.value.page = 1
    getAll(formInline.value)
  }

  // 当前页变化
  function handleCurrentChange(page: number) {
    formInline.value.page = page
    getAll(formInline.value)
  }

  // 新增
  function handleAdd() {
    currentData.value = null
    isEdit.value = false
    dialogVisible.value.form = true
  }

  // 编辑
  function handleEdit(row: RiskRule) {
    currentData.value = row
    isEdit.value = true
    dialogVisible.value.form = true
  }

  // 表单提交成功
  function handleFormSuccess() {
    dialogVisible.value.form = false
    getAll(formInline.value)
  }

  // 切换状态
  async function handleToggleStatus(row: RiskRule) {
    try {
      const newStatus = row.status === 1 ? 0 : 1
      const updateParam: RiskRuleUpdateParam = {
        id: row.id!,
        ruleName: row.ruleName!,
        ruleType: row.ruleType!,
        status: newStatus,
        rulePlaceOrderLimit: row.rulePlaceOrderLimit || '',
        ruleWaitPayLimit: row.ruleWaitPayLimit || '',
        ruleSkuLimit: row.ruleSkuLimit || '',
        rulePostSaleLimit: row.rulePostSaleLimit || '',
        ruleSwitchPostSale: row.ruleSwitchPostSale || 0,
        ruleSwitchSku: row.ruleSwitchSku || 0,
        ruleSwitchPlaceOrder: row.ruleSwitchPlaceOrder || 0,
        ruleSwitchWaitPay: row.ruleSwitchWaitPay || 0
      }

      const res = await updateRiskRule(updateParam)
      if (res.code === ApiStatus.success) {
        ElMessage.success('操作成功')
        getAll(formInline.value)
      } else {
        ElMessage.error(res.message || '操作失败')
      }
    } catch (error) {
      console.error('切换状态失败:', error)
      ElMessage.error('切换状态失败')
    }
  }

  // 删除
  async function handleDelete(row: RiskRule) {
    try {
      await ElMessageBox.confirm('确定要删除该规则吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })

      const deleteParam: RiskRuleDeleteParam = { id: row.id! }
      const res = await deleteRiskRule(deleteParam)
      if (res.code === ApiStatus.success) {
        ElMessage.success('删除成功')
        getAll(formInline.value)
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  }
</script>

<style lang="scss" scoped>
  .risk-rules-page {
    padding: 20px;
  }

  .header-actions {
    margin-bottom: 20px;
  }

  .operation-buttons {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;

    :deep(.btn-text) {
      margin-right: 0 !important;
    }
  }
</style>
